package com.xframe.xdal.core.model;

import com.xframe.xdal.core.util.StringUtil;

import java.util.Arrays;
import java.util.List;

/**
 * 功能描述:根据字符串生成CondiValueCollection和DbSortCollection对象
 *
 * @author lmx
 * @version 1.0
 * @date 2023-12-06
 */
public class BuildModelHelp {


    static final String END_CHAR = ";";
    static final String ITEM_CHAR = ":";
    static final String LIKE_SP_CHAR = "%";
    static final int STRUCT_COUNT = 3;
    /**
     * 功能描述:根据字符串生成CondiValueCollection对象
     *
     * @author lmx
     * @version 1.0
     * @date 2023-12-06
     * @param stringCondition  如delFlag:EQ:0;clientID:TQ:100;name:LIKE:xu;
     */
    public static ConditionValueCollection buildConditionValueCollection(String stringCondition){
        if(StringUtil.isEmpty(stringCondition)){
            return null;
        }
        ConditionValueCollection conditionValueCollection = new ConditionValueCollection();
        List<String> conditions = Arrays.asList(stringCondition.split(END_CHAR));
        conditions.forEach(item -> {
                    if (StringUtil.isNotEmpty(item)) {
                        List<String> eachParam = Arrays.asList(item.split(ITEM_CHAR));
                        if(eachParam.size() == STRUCT_COUNT) {
                            ConditionValue conditionValue = new ConditionValue();
                            conditionValue.setKeyName(eachParam.get(0));
                            conditionValue.setOperators(Operator.valueOf(eachParam.get(1)));
                            if (eachParam.get(1).equals(Operator.LIKE.name())) {
                                conditionValue.setVal(LIKE_SP_CHAR + eachParam.get(2) + LIKE_SP_CHAR);
                            } else {
                                conditionValue.setVal(eachParam.get(2));
                            }
                            conditionValueCollection.add(conditionValue);
                        }
                    }
                }
            );
        return conditionValueCollection;
    }

    /**
     * 功能描述:根据字符串生成DbSortCollection对象
     *
     * @author lmx
     * @version 1.0
     * @date 2023-12-06
     * @param stringDbSort  如createData:ASC;delFlag:DESC;
     */
    public static DbSortCollection buildDbSortCollection(String stringDbSort){
        if(StringUtil.isEmpty(stringDbSort)){
            return null;
        }
        List<String> conditions = Arrays.asList(stringDbSort.split(END_CHAR));
        DbSort[] dbSorts = new DbSort[conditions.size()];
        int index = 0;
        for(String condition : conditions){
            if(StringUtil.isNotEmpty(condition)){
                List<String> eachParam = Arrays.asList(condition.split(ITEM_CHAR));
                DbSort dbSort = new DbSort(eachParam.get(0), DbSort.SortDir.valueOf(eachParam.get(1).toUpperCase()),index + 1);
                dbSorts[index]=dbSort;
                index++;
            }
        }
        return new DbSortCollection(dbSorts);
    }
}
